import subprocess
import time

def continuous_ping(ip_address, interval=1, max_attempts=None):
    """
    持续对目标 IP 进行 ping 操作，直到手动停止或达到最大尝试次数。

    :param ip_address: 目标 IP 地址
    :param interval: 每次 ping 的间隔时间（秒）
    :param max_attempts: 最大尝试次数，None 表示无限循环
    """
    attempt_count = 0
    try:
        while max_attempts is None or attempt_count < max_attempts:
            attempt_count += 1
            try:
                output = subprocess.check_output(
                    ["ping", "-n", "1", "-w", "1000", ip_address],  # Windows
                    # ["ping", "-c", "1", "-W", "1", ip_address],  # Linux/Unix
                    stderr=subprocess.STDOUT,
                    universal_newlines=True
                )
                print(f"成功 ping 通 {ip_address} (尝试次数: {attempt_count})")
                print(output)
            except subprocess.CalledProcessError as e:
                print(f"无法 ping 通 {ip_address} (尝试次数: {attempt_count})")
                print(e.output)
            time.sleep(interval)
    except KeyboardInterrupt:
        print("用户中断了 ping 操作。")

# 示例：持续对局域网中的设备进行 ping 操作
continuous_ping("192.168.1.1", interval=2, max_attempts=10)